from datetime import datetime
from enum import Enum

from sqlalchemy import Column, String, SmallInteger, DateTime, Integer, Numeric

from app.model.base import BaseModel, db


class OrderStatus(Enum):
    WAIT_PAY = 0
    WAIT_SEND = 1
    WAIT_RECEIVE = 2
    FINISH = 3
    REQUEST_CANCEL = 4
    CANCELED = 5


order_status_map = ['待支付', '待发货', '待收货', '订单已完成', '正在申请退款', '订单已取消']


class Order(BaseModel):
    user_id = Column(String(40), nullable=False)
    product_id = Column(String(40), nullable=False)
    count = Column(Integer, default=1)
    single_price = Column(Numeric(10, 2), nullable=False)
    total_price = Column(Numeric(10, 2), nullable=False)
    status = Column(SmallInteger, nullable=False, default=OrderStatus.WAIT_PAY.value)
    package_code = Column(String(20))
    pay_time = Column(DateTime)
    send_package_time = Column(DateTime)
    finish_time = Column(DateTime)

    product_name = Column(String(40), nullable=False)
    product_img = Column(String(1000), nullable=False)
    user_realname = Column(String(10), nullable=False)
    user_address = Column(String(200), nullable=False)
    user_tel = Column(String(11), nullable=False)

    @property
    def status_text(self):
        return order_status_map[self.status]

    def finish(self):
        """
            完成订单（用户收货）
        """
        self.status = OrderStatus.FINISH.value
        self.finish_time = datetime.now()

    def send_package(self, package_code):
        """
            发货

        :param
            package_code: 快递单号
        """
        self.status = OrderStatus.WAIT_RECEIVE.value
        self.send_package_time = datetime.now()
        self.package_code = package_code

    def paid(self):
        """
            将订单切换到已付款状态
        """
        self.status = OrderStatus.WAIT_SEND.value
        self.pay_time = datetime.now()

    @staticmethod
    def create(product, user, count):
        order = Order()
        order.product_id = product.id
        order.count = count
        order.single_price = product.price
        order.total_price = product.price * int(count)
        order.user_id = user.id
        order.product_name = product.name
        order.product_img = product.img
        order.user_realname = user.realname
        order.user_address = user.address
        order.user_tel = user.tel
        return order

    def request_cancel(self):
        if OrderStatus(self.status).value > 0:
            self.status = OrderStatus.REQUEST_CANCEL.value
        else:
            self.status = OrderStatus.CANCELED.value

    def canceled(self):
        if OrderStatus(self.status) == OrderStatus.REQUEST_CANCEL:
            self.status = OrderStatus.CANCELED.value


if __name__ == '__main__':
    print(OrderStatus(1) == OrderStatus.WAIT_SEND)
    print(OrderStatus.WAIT_PAY.value)
